// Copyright (C) 2002-2005 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#include "CLMOMeshFileLoader.h"
#include <string.h>
#include <SMeshBuffer.h>
#include <SAnimatedMesh.h>
#include "fast_atof.h"	// that's one of the irrlicht headers
#include "ctype.h"

namespace irr
{
namespace scene
{



//! Constructor
CLMOMeshFileLoader::CLMOMeshFileLoader(io::IFileSystem* fs, video::IVideoDriver* driver)
: FileSystem(fs), Driver(driver), Mesh(0), mIsLightmap(false)
{
	if (FileSystem)
		FileSystem->grab();

	if (Driver)
		Driver->grab();
}



//! destructor
CLMOMeshFileLoader::~CLMOMeshFileLoader()
{
	if (FileSystem)
		FileSystem->drop();

	if (Driver)
		Driver->drop();

	if (Mesh)
		Mesh->drop();
}



//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".bsp")
bool CLMOMeshFileLoader::isALoadableFileExtension(const c8* filename)
{
	//return strstr(filename, ".obj")!=0 || strstr(filename, ".lmo")!=0;	// it could also still work with .obj files
	return strstr(filename, ".lmo")!=0;
}



//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IUnknown::drop() for more information.
IAnimatedMesh* CLMOMeshFileLoader::createMesh(io::IReadFile* file)
{
    if ( strstr(file->getFileName(), ".lmo") )
    {
	    // LOG.Debug("using lightmap\n");
        mIsLightmap = true;
    }
    else
    {
        mIsLightmap = false;
    }

	const s32 WORD_BUFFER_LENGTH = 255;
	c8 wordBuffer[WORD_BUFFER_LENGTH];

	if (Mesh)
	{
		Mesh->drop();
		Mesh = NULL;
	}
    Mesh = new SMesh();

	core::array< core::vector3df > vertexBuffer;
	core::array< core::vector2d<f32> > textureCoordBuffer;
	core::array< core::vector3df > normalsBuffer;
	SObjGroup * pCurrGroup = 0;
	SObjMtl * pCurrMtl = 0;

	s32 filesize = (s32)file->getSize();
	if (!filesize)
		return false;

    std::string infoStr("createMesh: ");
    infoStr += file->getFileName();
    infoStr += "\n";
	// LOG.Debug(infoStr);

	// ********************************************************************
	// Patch to locate the file in the same folder as the .obj.
	// If you load the file as "data/some.obj" and mtllib contains
	// "mtlname test.mtl" (as usual), the loading will fail. Instead it
	// must look for data/test.tml. This patch does exactly that.
	//
	// patch by mandrav@codeblocks.org
	// ********************************************************************
	core::stringc obj_fullname = file->getFileName();
	core::stringc obj_relpath = "";
	s32 pathend = obj_fullname.findLast('/');
	if (pathend == -1)
		pathend = obj_fullname.findLast('\\');
	if (pathend != -1)
		obj_relpath = obj_fullname.subString(0, pathend + 1);
	// ********************************************************************
	// end of mtl folder patch
	// ********************************************************************

	c8* pBuf = new c8[filesize];
	file->read((void*)pBuf, filesize);
	const c8* pBufEnd = pBuf+filesize;

	// Process obj information
	c8* pBufPtr = pBuf;
    while(pBufPtr && (pBufPtr-pBuf<filesize))
	{
		switch(pBufPtr[0])
		{
        case '#':               // comment
			break;

        case 'l':   // lmo - lightmap texture. Should belong in material and is only here, cuz i'm lazy
        {
            pBufPtr = goAndCopyNextWord(wordBuffer, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
            mLightmapTexture = wordBuffer;
            break;
        }

		case 'm':	// mtllib (material)
		{
			pBufPtr = goAndCopyNextWord(wordBuffer, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

			readMTL(wordBuffer, obj_relpath);
			break;
		}

		case 'v':               // v, vn, vt
			switch(pBufPtr[1])
			{
			case ' ':          // vertex
				{
					// vector
					c8 v1[WORD_BUFFER_LENGTH];
					c8 v2[WORD_BUFFER_LENGTH];
					c8 v3[WORD_BUFFER_LENGTH];
					pBufPtr = goAndCopyNextWord(v1, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(v2, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(v3, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

					vertexBuffer.push_back(core::vector3df(	-core::fast_atof(v1),
															core::fast_atof(v2),
															core::fast_atof(v3)));
				}
				break;

			case 'n':           // normal
				{
					// vector
					c8 v1[WORD_BUFFER_LENGTH];
					c8 v2[WORD_BUFFER_LENGTH];
					c8 v3[WORD_BUFFER_LENGTH];
					pBufPtr = goAndCopyNextWord(v1, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(v2, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(v3, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

					normalsBuffer.push_back(core::vector3df(-core::fast_atof(v1),
															core::fast_atof(v2),
															core::fast_atof(v3)));
				}
				break;

			case 't':           // texcoord
				{
					// vector
					c8 v1[WORD_BUFFER_LENGTH];
					c8 v2[WORD_BUFFER_LENGTH];
					pBufPtr = goAndCopyNextWord(v1, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(v2, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

					textureCoordBuffer.push_back(core::vector2df(	core::fast_atof(v1),
																	-core::fast_atof(v2)));
				}
				break;

			default:
				break;
			}
			break;

		case 'g':               // group
			// get name of group
			{
				c8 lineBuffer[WORD_BUFFER_LENGTH];
				copyLine(lineBuffer, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
				goAndCopyNextWord(wordBuffer, lineBuffer, WORD_BUFFER_LENGTH, pBufEnd);

				pCurrGroup = findOrAddGroup(wordBuffer);
				if ( 0 != pCurrMtl )
				{
					// Set meshbuffer's material to current active material
					if ( mIsLightmap )
					{
					    pCurrGroup->pMeshbufferLM->Material = pCurrMtl->material;
					}
					else
					{
                        pCurrGroup->pMeshbuffer->Material = pCurrMtl->material;
					}
				}
			}
			break;

		case 'u':				// usemtl
			if ( 0 != pCurrGroup )
			{
				// if there's a group being built up now,
				// get name of material
				pBufPtr = goAndCopyNextWord(wordBuffer, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

				// create a new group
				core::stringc groupNew = pCurrGroup->name;
				groupNew.append(wordBuffer);
				pCurrGroup = findOrAddGroup(wordBuffer);

				// retrieve the material
				pCurrMtl = findMtl( wordBuffer );
				if ( 0 != pCurrMtl )
				{
					// if material is present, assign it to current meshbuffer
					if ( mIsLightmap )
					{
					    pCurrGroup->pMeshbufferLM->Material = pCurrMtl->material;
					}
					else
					{
                        pCurrGroup->pMeshbuffer->Material = pCurrMtl->material;
					}
				}
				else
				{
				    if ( wordBuffer )
				    {
					    // LOG.InfoLn("could not find material", wordBuffer);
				    }
                    else
                    {
	                    // LOG.Info("missing material name\n");
                    }
                }
			}
			break;

		case 'f':               // face
			if ( 0 != pCurrGroup )
			{
			    core::array<s32> vertexIndices;
				c8 vertexWord[WORD_BUFFER_LENGTH];	// for retriving vertex data
				video::S3DVertex v;
				video::S3DVertex2TCoords v2t;
				s32 currentVertexCount = mIsLightmap ? pCurrGroup->pMeshbufferLM->Vertices.size() : pCurrGroup->pMeshbuffer->Vertices.size();
				u32 facePointCount = 0;	// number of vertices in this face

				// Assign vertex colour to the current active material's diffuse colour
				if ( pCurrMtl)
				{
				    if ( mIsLightmap )
                        v2t.Color = pCurrMtl->material.DiffuseColor;
                    else
                        v.Color =  pCurrMtl->material.DiffuseColor;
				}

				// get all vertices data in this face (current line of obj file)
				copyLine(wordBuffer, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);
				c8 * pLinePtr = wordBuffer;

				// read in all vertices
				pLinePtr = goNextWord(pLinePtr, pBufEnd);
				while (0 != pLinePtr[0])
				{
				    // Array to communicate with retrieveVertexIndices()
                    // sends the buffer sizes and gets the actual indices
                    // if index not set returns -1
                    s32 Idx[4];
                    Idx[0]=vertexBuffer.size();
                    Idx[1]=textureCoordBuffer.size();
                    Idx[2]=normalsBuffer.size();
                    Idx[3]=-1;

					// read in next vertex's data
					copyWord(vertexWord, pLinePtr, WORD_BUFFER_LENGTH, pBufEnd);
					// this function will also convert obj's 1-based index to c++'s 0-based index
					retrieveVertexIndices(vertexWord, Idx, pBufEnd);
					if ( mIsLightmap )
					{
                        if ( -1 != Idx[0] )
                        {
                            v2t.Pos = vertexBuffer[Idx[0]];
                        }
                        if ( -1 != Idx[1] )
                        {
                            v2t.TCoords = textureCoordBuffer[Idx[1]];
                        }
                        if ( -1 != Idx[2] )
                        {
                            v2t.Normal = normalsBuffer[Idx[2]];
                        }
                        if ( -1 != Idx[3] )
                        {
                            v2t.TCoords2 = textureCoordBuffer[Idx[3]];
                        }

                        // test to reduce number of indices, try to find if the vertex is already available
//                        bool available = false;
//                        video::S3DVertex2TCoords * vertices = (video::S3DVertex2TCoords *)pCurrGroup->pMeshbufferLM->getVertices();
//                        for ( s32 i=0; i < currentVertexCount; ++i )
//                        {
//                            if ( vertices[i] == v2t )
//                            {
//                                vertexIndices.push_back(i);
//                                available = true;
//                                break;
//                            }
//                        }
//
//                        if ( !available )
//                        {
//                            pCurrGroup->pMeshbufferLM->Vertices.push_back(v2t);
//                            vertexIndices.push_back(pCurrGroup->pMeshbufferLM->Vertices.size()-1);
//                        }
                        pCurrGroup->pMeshbufferLM->Vertices.push_back(v2t);
                    }
					else
					{
                        if ( -1 != Idx[0] )
                        {
                            v.Pos = vertexBuffer[Idx[0]];
                        }
                        if ( -1 != Idx[1] )
                        {
                            v.TCoords = textureCoordBuffer[Idx[1]];
                        }
                        if ( -1 != Idx[2] )
                        {
                            v.Normal = normalsBuffer[Idx[2]];
                        }

//                        // test to reduce number of indices, try to find if the vertex is already available
//                        bool available = false;
//                        video::S3DVertex * vertices = (video::S3DVertex*)pCurrGroup->pMeshbuffer->getVertices();
//                        for ( s32 i=0; i < currentVertexCount; ++i )
//                        {
//                            if ( vertices[i] == v )
//                            {
//                                vertexIndices.push_back(i);
//                                available = true;
//                                break;
//                            }
//                        }
//
//                        if ( !available )
//                        {
//                            pCurrGroup->pMeshbuffer->Vertices.push_back(v);
//                            vertexIndices.push_back(pCurrGroup->pMeshbuffer->Vertices.size()-1);
//                        }
                        pCurrGroup->pMeshbuffer->Vertices.push_back(v);
					}
					++facePointCount;

					// go to next vertex
					pLinePtr = goNextWord(pLinePtr, pBufEnd);
				}

                core::array<u16> * indices = NULL;
                if ( mIsLightmap )
                {
                    indices = &(pCurrGroup->pMeshbufferLM->Indices);
                }
                else
                {
                    indices = &(pCurrGroup->pMeshbuffer->Indices);
                }

//                // Add indices for first 3 vertices
                indices->push_back( currentVertexCount );
                indices->push_back( ( facePointCount - 1 ) + currentVertexCount );
                indices->push_back( ( facePointCount - 2 ) + currentVertexCount );
                // Add indices for subsequent vertices
                for ( u32 i = 0; i < facePointCount - 3; ++i )
                {
                    indices->push_back( currentVertexCount );
                    indices->push_back( ( facePointCount - 2 - i ) + currentVertexCount );
                    indices->push_back( ( facePointCount - 3 - i ) + currentVertexCount );
                }
//                // Add indices for first 3 vertices
//                indices->push_back( vertexIndices[0] );
//                indices->push_back( vertexIndices[facePointCount-1] );
//                indices->push_back( vertexIndices[facePointCount-2] );
//                // Add indices for subsequent vertices
//                for ( u32 i = 0; i < facePointCount - 3; ++i )
//                {
//                    indices->push_back( vertexIndices[0] );
//                    indices->push_back( vertexIndices[facePointCount-2-i] );
//                    indices->push_back( vertexIndices[facePointCount-3-i] );
//                }
			}

			break;

		default:
			break;
		}	// end switch(pBufPtr[0])
        pBufPtr = goNextLine(pBufPtr, pBufEnd);
	}	// end while(pBufPtr && (pBufPtr-pBuf<filesize))

	// Combine all the groups (meshbuffers) into the mesh
	for ( u32 m = 0; m < groups.size(); m++ )
	{
		// LOG.DebugLn("group: ", groups[m]->name.c_str());
	    if ( mIsLightmap )
	    {
            if ( groups[m]->pMeshbufferLM->getIndices() > 0 )
            {
//                fprintf(stderr, "indices: %d vertices: %d\n", groups[m]->pMeshbufferLM->getIndexCount(), groups[m]->pMeshbufferLM->getVertexCount() );

                groups[m]->pMeshbufferLM->recalculateBoundingBox();
                Mesh->addMeshBuffer( groups[m]->pMeshbufferLM );
            }
	    }
	    else
	    {
            if ( groups[m]->pMeshbuffer->getIndices() > 0 )
            {
  //              fprintf(stderr, "indices: %d vertices: %d\n", groups[m]->pMeshbuffer->getIndexCount(), groups[m]->pMeshbuffer->getVertexCount() );

                groups[m]->pMeshbuffer->recalculateBoundingBox();
                Mesh->addMeshBuffer( groups[m]->pMeshbuffer );
            }
	    }
	}

	// Create the Animated mesh if there's anything in the mesh
	SAnimatedMesh* pAM = 0;
    if ( 0 != Mesh->getMeshBufferCount() )
    {
        Mesh->recalculateBoundingBox();
        pAM = new SAnimatedMesh();
        pAM->Type = EAMT_OBJ;
        pAM->addMesh(Mesh);
        pAM->recalculateBoundingBox();
    }

	// Clean up the allocate obj file contents
	delete [] pBuf;
	// more cleaning up
	cleanUp();

	if ( Mesh )
	{
        Mesh->drop();
        Mesh = 0;
	}

    return pAM;
}


void CLMOMeshFileLoader::readMTL(const c8* pFileName, core::stringc relPath)
{
    std::string strInfo("read material ");
    strInfo += pFileName;
    strInfo += "\n";
	// LOG.Debug(strInfo);

	const s32 WORD_BUFFER_LENGTH = 255;

	io::IReadFile * pMtlReader;
	if (FileSystem->existFile(pFileName))
		pMtlReader = FileSystem->createAndOpenFile(pFileName);
	else
		// try to read in the relative path, the .obj is loaded from
		pMtlReader = FileSystem->createAndOpenFile((relPath + pFileName).c_str());
	if (!pMtlReader)	// fail to open and read file
		return;

	s32 filesize = (s32)pMtlReader->getSize();
	if (!filesize)
		return;

	c8* pBuf = new c8[filesize];
	pMtlReader->read((void*)pBuf, filesize);
	const c8* pBufEnd = pBuf+filesize;

	SObjMtl * pCurrMaterial = 0;

	c8* pBufPtr = pBuf;
	while(pBufPtr && (pBufPtr-pBuf<filesize))
	{
		switch(pBufPtr[0])
		{
        case 'n':               // newmtl
			{
				// if there's an existing material, store it first
				if ( 0 != pCurrMaterial )
				{
					materials.push_back( *pCurrMaterial );
					delete pCurrMaterial;
				}

				// extract new material's name
				c8 mtlNameBuf[WORD_BUFFER_LENGTH];
				pBufPtr = goAndCopyNextWord(mtlNameBuf, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

				pCurrMaterial = new SObjMtl;

				pCurrMaterial->name = mtlNameBuf;
//				pCurrMaterial->material.AmbientColor = video::SColor(255, (s32)(0.2*255.f), (s32)(0.2*255.f), (s32)(0.2*255.f));
				pCurrMaterial->material.AmbientColor = video::SColor(255, 255, 255, 255);
//				pCurrMaterial->material.DiffuseColor = video::SColor(255, (s32)(0.8*255.f), (s32)(0.8*255.f), (s32)(0.8*255.f));
                pCurrMaterial->material.DiffuseColor = video::SColor(255, 255, 255, 255);
				pCurrMaterial->material.SpecularColor = video::SColor(255,0,0,0);
				pCurrMaterial->material.Shininess = 20.f;
                pCurrMaterial->material.MaterialTypeParam = 0.02f;  // just a value that works for me
                pCurrMaterial->material.EmissiveColor = video::SColor(255,0,0,0);  // this should be the correct value

                if ( mIsLightmap )
                {
                    core::stringc dummy(mPathTextures);
                    dummy.append(mLightmapTexture);
	                pCurrMaterial->material.Texture[1] = Driver->getTexture( (c8*)dummy.c_str() );
                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_LIGHTING_M2;

//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_ADD;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_M2;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_M4;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_LIGHTING;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_LIGHTING_M2;
//                    pCurrMaterial->material.MaterialType = video::EMT_LIGHTMAP_LIGHTING_M4;
                }
			}
            break;
        case 'i':		// illum - illuminationSRC_ALPHA
            if ( 0 != pCurrMaterial )
            {
                const s32 COLOR_BUFFER_LENGTH = 16;
                c8 illumStr[COLOR_BUFFER_LENGTH];

                pBufPtr = goAndCopyNextWord(illumStr, pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
                pCurrMaterial->illumination = (c8)atol(illumStr);
            }
            break;

        case 'N':
			if ( 0 != pCurrMaterial )
			{
			    switch(pBufPtr[1])
			    {
			        case 's': // Ns - shininess
			        {
                        const s32 COLOR_BUFFER_LENGTH = 16;
                        c8 nsStr[COLOR_BUFFER_LENGTH];

                        pBufPtr = goAndCopyNextWord(nsStr, pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
                        f32 shininessValue = core::fast_atof(nsStr);

                        // wavefront shininess is from [0, 1000], so scale for OpenGL
                        shininessValue *= 0.128;
                        pCurrMaterial->material.Shininess = shininessValue;
                        break;
			        }
			    }
			}

            break;
        case 'K':
            if ( 0 != pCurrMaterial )
			{
				switch(pBufPtr[1])
				{
				case 'd':		// Kd = diffuse
					{
					    if ( pCurrMaterial->illumination != 4 )
                            pBufPtr = readColor(pBufPtr, pCurrMaterial->material.DiffuseColor, pBufEnd);
					}
					break;

				case 's':		// Ks = specular
					{
						pBufPtr = readColor(pBufPtr, pCurrMaterial->material.SpecularColor, pBufEnd);
					}
					break;

				case 'a':		// Ka = ambience
					{
					    video::SColor col;
					    if ( pCurrMaterial->illumination == 4 )
					    {
					        pBufPtr=readColor(pBufPtr, col, pBufEnd);
					        if ( col.getRed() != 0 || col.getGreen() != 0 || col.getBlue() != 0 )
					        {
					            pCurrMaterial->material.AmbientColor = video::SColor(255,0,0,0);
					            pCurrMaterial->material.EmissiveColor = col;
					        }
					    }
                      else
                        {
                            pBufPtr=readColor(pBufPtr, pCurrMaterial->material.AmbientColor, pBufEnd);
                        }
					}
					break;

				default:
					break;
				}	// end switch(pBufPtr[1])
			}	// end case 'K': if ( 0 != pCurrMaterial )...
            break;

        case 'b':           // bump
		case 'm':			// map_Kd - diffuse texture map
			if ( 0 != pCurrMaterial )
			{
			    char type=0;
			    if ( pBufPtr[0] == 'b' )
                    type = 1;
				if (!strncmp(pBufPtr,"map_bump",8))
					type = 1;
				else if (!strncmp(pBufPtr,"map_d",5))
					type = 2;
				else if (!strncmp(pBufPtr,"map_refl",8))
					type = 2;

				// extract new material's name
				c8 textureNameBuf[WORD_BUFFER_LENGTH];
				pBufPtr = goAndCopyNextWord(textureNameBuf, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);

                core::stringc dummy(mPathTextures);
                dummy.append(textureNameBuf);
                video::ITexture * pTexture = Driver->getTexture( (c8*)dummy.c_str() );
                if ( !pTexture )
                {
                    core::stringc failMsg("readMTL: could not get texture");
                    failMsg += dummy;
                    failMsg += "\n";
	                // LOG.Debug(failMsg.c_str());
                }

				//video::ITexture * pTexture = Driver->getTexture( textureNameBuf );
				if ( 0 != pTexture )
                {
                    if (type==0)
                    {
	                    pCurrMaterial->material.Texture[0] = pTexture;
                    }
					else if (type==1 && !mIsLightmap)
					{
                        c8 dummyBuf[WORD_BUFFER_LENGTH];
                        pBufPtr = goAndCopyNextWord(dummyBuf, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);    //-bm
                        pBufPtr = goAndCopyNextWord(dummyBuf, pBufPtr, WORD_BUFFER_LENGTH, pBufEnd);    // value
                        pCurrMaterial->material.MaterialTypeParam=core::fast_atof(dummyBuf);

					    video::IMaterialRenderer* renderer = Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
                        if (renderer && renderer->getRenderCapability() == 0)
                        {
// TODO: currently not working, as once normal maps are selected other materials are also
// rendered using normal maps (which ain't a problem of this loader, but looks wrong)
                            //Driver->makeNormalMapTexture(pTexture);
//                            pCurrMaterial->material.Texture[1] = pTexture;
//                            pCurrMaterial->material.MaterialType = video::EMT_PARALLAX_MAP_SOLID;
                        }
                        else
                        {
                            // TODO
                        }
					}
					else if (type==2)
					{
						pCurrMaterial->material.Texture[0] = pTexture;
						if ( !mIsLightmap )
						{
                            pCurrMaterial->material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR;
						}
					}
					// Set diffuse material colour to white so as not to affect texture colour
					// Because Maya set diffuse colour Kd to black when you use a diffuse colour map
					// But is this the right thing to do?
					//pCurrMaterial->material.DiffuseColor.set(pCurrMaterial->material.DiffuseColor.getAlpha(), 255, 255, 255 );
				}
			}
			break;

        case 'd':				// d - transparency
			if ( 0 != pCurrMaterial )
			{
				const s32 COLOR_BUFFER_LENGTH = 16;
				c8 dStr[COLOR_BUFFER_LENGTH];

				pBufPtr = goAndCopyNextWord(dStr, pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
				f32 dValue = core::fast_atof(dStr);

				pCurrMaterial->material.DiffuseColor.setAlpha( (s32)(dValue * 255) );
				if (dValue<1.0f && !mIsLightmap)
                    pCurrMaterial->material.MaterialType = irr::video::EMT_TRANSPARENT_VERTEX_ALPHA;
			}

            break;

		case 'T':
			if ( 0 != pCurrMaterial )
			{
				switch ( pBufPtr[1] )
				{
				case 'f':		// Tf - Transmitivity
					const s32 COLOR_BUFFER_LENGTH = 16;
					c8 redStr[COLOR_BUFFER_LENGTH];
					c8 greenStr[COLOR_BUFFER_LENGTH];
					c8 blueStr[COLOR_BUFFER_LENGTH];

					pBufPtr = goAndCopyNextWord(redStr,   pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(greenStr, pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
					pBufPtr = goAndCopyNextWord(blueStr,  pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);

					f32 transparency = ( core::fast_atof(redStr) + core::fast_atof(greenStr) + core::fast_atof(blueStr) ) / 3;

					pCurrMaterial->material.DiffuseColor.setAlpha( (s32)(transparency * 255) );
					//pCurrMaterial->material.MaterialType = irr::video::EMT_TRANSPARENT_VERTEX_ALPHA;  // TODO: why doesn't it work?
				}
			}

            break;

        case 'A': // (alphablending), NOT an original .mtl parameter, but useful in Irrlicht so i added it to the format
            {
                const s32 VALUE_BUFFER_LENGTH = 16;
                c8 aStr[VALUE_BUFFER_LENGTH];

                pBufPtr = goAndCopyNextWord(aStr, pBufPtr, VALUE_BUFFER_LENGTH, pBufEnd);
                pCurrMaterial->material.MaterialTypeParam = core::fast_atof(aStr);
            }
            break;

        default:               // comments or not recognised
			break;
		}	// end switch(pBufPtr[0])
        pBufPtr = goNextLine(pBufPtr, pBufEnd);
	}	// end while (pBufPtr)

	// end of file. if there's an existing material, store it
	if ( 0 != pCurrMaterial )
	{
		materials.push_back( *pCurrMaterial );
		delete pCurrMaterial;
		pCurrMaterial = 0;
    }

	delete [] pBuf;
	pMtlReader->drop();
}

c8* CLMOMeshFileLoader::readColor(c8* pBufPtr, video::SColor& color, const c8* pBufEnd)
{
	const s32 COLOR_BUFFER_LENGTH = 16;
	c8 colStr[COLOR_BUFFER_LENGTH];

	//color.setAlpha(255);
	color.setAlpha(255);
	pBufPtr = goAndCopyNextWord(colStr,   pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
//	color.setRed((s32)(255-core::fast_atof(colStr) * 255));
	color.setRed((s32)(core::fast_atof(colStr) * 255));
	pBufPtr = goAndCopyNextWord(colStr,   pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
//	color.setGreen((s32)(255-core::fast_atof(colStr) * 255));
	color.setGreen((s32)(core::fast_atof(colStr) * 255));
	pBufPtr = goAndCopyNextWord(colStr,   pBufPtr, COLOR_BUFFER_LENGTH, pBufEnd);
//	color.setBlue((s32)(255-core::fast_atof(colStr) * 255));
	color.setBlue((s32)(core::fast_atof(colStr) * 255));

	return pBufPtr;
}

CLMOMeshFileLoader::SObjMtl * CLMOMeshFileLoader::findMtl(c8* pMtlName)
{
	for (u32 i = 0; i < materials.size(); ++i)
	{
		if ( materials[i].name == pMtlName )
		{
			return &materials[i];
		}
	}
	return 0;
}


CLMOMeshFileLoader::SObjGroup* CLMOMeshFileLoader::addGroup(c8* pGroupName)
{
	SObjGroup * group = new SObjGroup();
	group->name = pGroupName;
	if ( mIsLightmap )
	{
	    group->pMeshbufferLM = new SMeshBufferLightMap();
	}
	else
	{
        group->pMeshbuffer = new SMeshBuffer();
	}

	groups.push_back(group);
	return group;
}


CLMOMeshFileLoader::SObjGroup * CLMOMeshFileLoader::findGroup(c8* pGroupName)
{
	for (u32 i = 0; i < groups.size(); ++i)
	{
		if ( groups[i]->name == pGroupName )
		{
			return groups[i];
		}
	}
	return 0;
}


CLMOMeshFileLoader::SObjGroup * CLMOMeshFileLoader::findOrAddGroup(c8* pGroupName)
{
	SObjGroup * pGroup = findGroup( pGroupName );
	if ( 0 != pGroup )
	{
		// group found, return it
		return pGroup;
	}
	// group not found, create a new group
	return addGroup( pGroupName );
}


c8* CLMOMeshFileLoader::goFirstWord(c8* buf, const c8* pBufEnd)
{
	s32 i = 0;
	// skip pass non-printable characters
	while(buf[i] && (buf[i]==' ' || buf[i]=='\n' || buf[i]=='\r' || buf[i]=='\t'))
	{
		if ( &(buf[i]) == pBufEnd )
		{
			// end of buffer check
			return 0;
		}
		++i;
	}

	return &buf[i];
}


c8* CLMOMeshFileLoader::goNextWord(c8* buf, const c8* pBufEnd)
{
	if (!buf)
		return 0;

	s32 i = 0;
	// look for non-printable characters
	while(buf[i])
	{
		if ( &(buf[i]) == pBufEnd )
		{
			// end of buffer check
			return 0;
		}
		if (buf[i]==' ' || buf[i]=='\n' || buf[i]=='\r' || buf[i]=='\t')
			break;

		++i;
	}

	// look for printable character after non-printable character
	c8* nextWord = goFirstWord(&buf[i], pBufEnd);
	// if can't find, return null
	return nextWord == buf ? 0 : nextWord;
}


c8* CLMOMeshFileLoader::goNextLine(c8* buf, const c8* pBufEnd)
{
    if ( !buf )
        return 0;
	// Have to use pointer to pointer in parameter or else string address won't be changed
	s32 i=0;
	// look for newline characters
	while(buf[i])
	{
		if ( &(buf[i]) == pBufEnd )
		{
			// end of buffer check
			return 0;
		}
		if (buf[i]=='\n' || buf[i]=='\r')
		{
			// found it, so skip pass it
			break;
		}

		++i;
	}
	do
	{
	    ++i;
	    if ( pBufEnd == buf+i )
	    {
	        // check for end of buffer
	        return (c8*)pBufEnd;
	    }
	}
	while ( isspace(buf[i]));

	return &buf[i];
}


void CLMOMeshFileLoader::copyWord(c8* outBuf, const c8* inBuf, s32 outBufLength, const c8* pBufEnd)
{
	if (!inBuf)
		return;

	s32 i = 0;
	while(inBuf[i])
	{
		if (inBuf[i]==' ' || inBuf[i]=='\n' || inBuf[i]=='\r' || inBuf[i]=='\t' || &(inBuf[i]) == pBufEnd)
			break;
		++i;
	}

	for (s32 j=0; j<i && j<outBufLength-1; ++j)
		outBuf[j] = inBuf[j];

	outBuf[i] = 0x0;
}


void CLMOMeshFileLoader::copyLine(c8* outBuf, const c8* inBuf, s32 outBufLength, const c8* pBufEnd)
{
	if (!inBuf)
		return;

	s32 i = 0;
	while(inBuf[i])
	{
		if (inBuf[i]=='\n' || inBuf[i]=='\r' || &(inBuf[i]) == pBufEnd)
			break;
		++i;
	}

	for (s32 j=0; j<i && j<outBufLength-1; ++j)
		outBuf[j] = inBuf[j];

	outBuf[i] = 0x0;
}


c8* CLMOMeshFileLoader::goAndCopyNextWord(c8* outBuf, c8* inBuf, s32 outBufLength, const c8* pBufEnd)
{
	inBuf = goNextWord(inBuf, pBufEnd);
	copyWord(outBuf, inBuf, outBufLength, pBufEnd);
	return inBuf;
}

bool CLMOMeshFileLoader::retrieveVertexIndices(c8* pVertexData, s32* pIdx, const c8* pBufEnd)
{
	c8 word[16] = "";
	c8* pChar = goFirstWord(pVertexData, pBufEnd);
	c8 idxType = 0;		// 0 = posIdx, 1 = texcoordIdx, 2 = normalIdx, 3 = texCoordIdx2 for .lmo files
	s32 index;

	u32 i = 0;
	while ( pChar != pBufEnd )
	{
		if ( (isdigit(*pChar)) || (*pChar == '-') )
		{
			// build up the number
			word[i++] = *pChar;
		}
		else if ( *pChar == '/' || *pChar == '\0' )
		{
			// number is completed. Convert and store it
			word[i] = '\0';
			// if no number was found index will become 0 and later on -1 by decrement
			index = atoi( word );
			if (index<0)
				index += pIdx[idxType];
			else
				--index;
			pIdx[idxType] = index;

			// reset the word
			word[0] = '\0';
			i = 0;

			// go to the next kind of index type
			if (*pChar == '/')
			{
			    ++idxType;
				if ( (!mIsLightmap && idxType > 2 ) || idxType > 3 )
				{
					// error checking, shouldn't reach here unless file is wrong
					idxType = 0;
				}
			}
			else if (*pChar == '\0')
			{
				// set all missing values to disable (=-1)
				while (++idxType < 3)
					pIdx[idxType]=-1;
                if ( mIsLightmap && idxType == 2 )
                {
                    idxType = 3;
                    pIdx[idxType]=-1;
                }

				++pChar;
				break; // while
			}
		}

		// go to the next char
		++pChar;
	}

	return true;
}

void CLMOMeshFileLoader::cleanUp()
{
	materials.clear();
	for (u32 i = 0; i < groups.size(); ++i )
	{
	    if ( groups[i]->pMeshbuffer )
	    {
            groups[i]->pMeshbuffer->drop();
            groups[i]->pMeshbuffer = NULL;
	    }
	    if ( groups[i]->pMeshbufferLM )
	    {
	        groups[i]->pMeshbufferLM->drop();
            groups[i]->pMeshbufferLM = NULL;
	    }
		delete groups[i];
	}
	groups.clear();
}


} // end namespace scene
} // end namespace irr

